<template>
  <a-drawer
    v-model:visible="isDrawer"
    :width="width"
    :title="title"
    unmountOnClose
    placement="right"
    :ok-loading="subLoading"
    :on-before-ok="formSubmit"
    @cancel="handleReset"
  >
    <a-form
      :model="formParams"
      :rules="rules"
      ref="formRef"
      label-placement="left"
      :label-width="80"
    >
      <a-form-item label="租户编码" field="tenantCode">
        <a-input placeholder="请输入租户编码" v-model="formParams.tenantCode" />
      </a-form-item>
      <a-form-item label="租户名称" field="tenantName">
        <a-input placeholder="请输入租户名称" v-model="formParams.tenantName" />
      </a-form-item>
      <a-form-item label="开始时间" field="beginDate">
        <a-date-picker v-model="formParams.beginDate" show-time allow-clear />
      </a-form-item>
      <a-form-item label="结束时间" field="endDate">
        <a-date-picker v-model="formParams.endDate" show-time allow-clear />
      </a-form-item>
      <a-form-item label="状态" field="tenantStatus">
        <a-radio-group type="button" v-model="formParams.tenantStatus" name="tenantStatusGroup">
          <a-radio :key="0" :value="0">启用</a-radio>
          <a-radio :key="1" :value="1">禁用</a-radio>
        </a-radio-group>
      </a-form-item>
    </a-form>
  </a-drawer>
</template>

<script lang="ts" setup>
  import { ref, onMounted } from 'vue';
  import { Message } from '@arco-design/web-vue';
  import type { formParamsType } from './types';
  import { cloneDeep } from 'lodash-es';
  import { addTenant, editTenant, tenantInfo } from '@/api/tenant/index';
  import { formatToDateTime } from '@/utils/dateUtil';

  const rules = {
    tenantCode: {
      required: true,
      message: '请填写租户编码',
      trigger: 'blur',
    },
    tenantName: {
      required: true,
      message: '请填写租户名称',
      trigger: 'blur',
    },
    beginDate: {
      required: true,
      message: '请选择开始时间',
      trigger: 'change',
      type: 'number',
    },
    endDate: {
      required: true,
      message: '请选择结束时间',
      trigger: 'change',
      type: 'number',
    },
  };

  const emit = defineEmits(['change']);

  defineProps({
    title: {
      type: String,
      default: '添加租户',
    },
    width: {
      type: Number,
      default: 450,
    },
    permissionList: {
      type: Array,
    },
  });

  const defaultValueRef = () => ({
    tenantId: null,
    beginDate: undefined,
    endDate: undefined,
    tenantCode: '',
    tenantStatus: 0,
    tenantName: '',
  });

  const formRef: any = ref(null);
  const isDrawer = ref(false);
  const subLoading = ref(false);

  const formParams = ref<formParamsType>(defaultValueRef());

  function openDrawer(tenantId?) {
    if (tenantId) {
      formParams.value.tenantId = tenantId;
      getInfo();
      return;
    }
    isDrawer.value = true;
  }

  function closeDrawer() {
    isDrawer.value = false;
  }

  function formSubmit(done) {
    formRef.value.validate((errors) => {
      if (errors) {
        Message.error('请填写完整信息');
        subLoading.value = false;
        return done(false);
      }
      const params = cloneDeep(formParams.value);
      params.beginDate = formatToDateTime(params.beginDate);
      params.endDate = formatToDateTime(params.endDate);
      if (formParams.value.tenantId) {
        editTenant(params)
          .then((_) => {
            Message.success('编辑成功');
            emit('change');
            handleReset();
            return done(true);
          })
          .catch(() => {
            return done(false);
          });
      } else {
        addTenant(params)
          .then((_) => {
            Message.success('添加成功');
            emit('change');
            handleReset();
            return done(true);
          })
          .catch(() => {
            return done(false);
          });
      }
    });
  }

  function handleReset() {
    formRef.value.resetFields();
    formParams.value = Object.assign(formParams.value, defaultValueRef());
  }

  function getInfo() {
    tenantInfo({ id: formParams.value.tenantId }).then((res) => {
      const info = {
        tenantId: res.tenantId,
        tenantName: res.tenantName,
        tenantCode: res.tenantCode,
        beginDate: new Date(res.beginDate).getTime(),
        endDate: new Date(res.endDate).getTime(),
        tenantStatus: res.tenantStatus,
      };
      formParams.value = info;
      isDrawer.value = true;
    });
  }

  onMounted(() => {});

  defineExpose({
    openDrawer,
    closeDrawer,
  });
</script>
